package com.dragon.codefx.config;

import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.net.URL;

@Component
public class JavaFXConfig {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private SystemTrayManager systemTrayManager;

    @Autowired
    private PageManager pageManager;

    public void start(Stage stage) throws Exception {
        // 设置不自动退出，防止所有窗口关闭时程序退出
        Platform.setImplicitExit(false);
        pageManager.setPrimaryStage(stage);
        // 设置主舞台到托盘管理器
        systemTrayManager.setPrimaryStage(stage);
        // 设置应用程序图标
        setApplicationIcon(stage);

        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/IndexView.fxml"));
        fxmlLoader.setControllerFactory(applicationContext::getBean);
        Scene scene = new Scene(fxmlLoader.load(), 800, 600);
        stage.setTitle("代码生成器");
        stage.setScene(scene);

        // 设置窗口初始大小
        stage.setWidth(1200);
        stage.setHeight(800);
        // 设置窗口最小和最大尺寸限制
        stage.setMinWidth(400);
        stage.setMinHeight(300);
        // 设置窗口是否可调整大小
        stage.setResizable(false);
        // 设置窗口关闭事件（隐藏到托盘而不是直接退出）
        stage.setOnCloseRequest(event -> {
            // 阻止默认关闭行为
            event.consume();
            stage.hide();
        });
        // 可选：设置窗口居中显示
        stage.centerOnScreen();
        stage.show();
    }

    private void setApplicationIcon(Stage stage) {
        try {
            // 尝试从资源文件加载图标
            URL iconResource = getClass().getResource("/icons/app-icon.png");
            if (iconResource != null) {
                Image icon = new Image(iconResource.toExternalForm());
                stage.getIcons().add(icon);
            }
        } catch (Exception ignore) {
        }
    }
}